package com.mlm.mlmapp.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.DresserClickListener;
import com.mlm.mlmapp.adapter.view.listener.OnNextPageShouldDownloadListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

@EActivity(R.layout.dresser_comments_list)
public class DresserCommentsListActivity extends BaseActivity implements
		HTTPCons, DresserClickListener, OnNextPageShouldDownloadListener {
	public static final int REQUEST_CODE = 11;
	@DimensionRes(R.dimen.recyclerview_sylist_space)
	float commentImagesMargin;
	@DimensionRes
	float comments_images_edge;
	@ViewById
	TextView tv_no_title;
	private AQuery aq;
	private DresserCommentsListAdapter adapter;
	List<JSONObject> dresserCommentsListDataset;
	private AjaxCallback<JSONArray> commentsCB;
	private boolean isMaxPage = false;
	private int coutPerPage = 3;
	@ViewById
	RecyclerView rv_comments;
	@DimensionRes(R.dimen.recyclerview_mycomments_space)
	float recyclerview_mycomments_space;
	@DimensionRes(R.dimen.recyclerview_dressercomments_header_padding)
	float leftPadding;
	@ColorRes
	int blacktext;

	@Pref
	Prefs_ myPrefs;
	@DimensionRes
	float comments_title_padding;
	@ViewById
	ImageView iv_headimg;
	@ViewById
	Button iv_appointment;
	@ViewById
	ImageView iv_back;
	@ViewById
	ImageView iv_collection;
	@ViewById
	TextView tv_name;
	@ViewById
	TextView tv_post;
	@ViewById
	TextView tv_words;
	@ViewById
	TextView tv_collections;
	@ViewById
	TextView tv_orders;
	@ViewById
	TextView tv_type;
	@ViewById
	TextView tv_price;
	@ViewById
	Button btn_coupon;
	// @ViewById
	// RatingBar ratingBar1;
	@Extra
	String dresserid;

	@AfterViews
	public void init() {
		String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}

		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		aq.progress(new AQProgressDialog(this)).ajax(get_dresser_comments_header_action + "?stylistinfoId="
				+ dresserid, JSONObject.class, new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject json, AjaxStatus status) {
				// TODO Auto-generated method stub

				if (status.getCode() == -101) {
					Toast.makeText(aq.getContext(), "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_SHORT).show();
				} else {
					tv_name.setText(CommonUtils.getJsonString(json, "name"));

					tv_post.setText(CommonUtils.getJsonString(json, "leveName"));
					tv_words.setText(CommonUtils.getJsonString(json,
							"introduce"));

					tv_orders.setText(DresserCommentsListActivity.this
							.getString(R.string.txt_order,
									CommonUtils.getJsonInt(json, "bought")));
					tv_collections.setText(DresserCommentsListActivity.this
							.getString(R.string.txt_collection,
									CommonUtils.getJsonInt(json, "collected")));
					tv_price.setText(DresserCommentsListActivity.this
							.getString(R.string.txt_price,
									CommonUtils.getJsonInt(json, "priceMast")));
					// ratingBar1.setRating(json.getInt("starLevel"));

					aq.id(iv_headimg).image(
							CommonUtils.getJsonString(json, "iconPhotoUrl"),
							true, true, 0, 0, null, Constants.FADE_IN);

					// final JSONObject coupon = json.getJSONObject("coupon");
					// if (coupon.isNull("couponName")) {
					// btn_coupon.setVisibility(View.INVISIBLE);
					// } else {
					// btn_coupon.setText(coupon.getString("couponName"));
					// }
					// btn_coupon.setOnClickListener(new OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// // TODO Auto-generated method stub
					// // coupon click
					// try {
					// CouponGetListActivity_
					// .intent(DresserCommentsListActivity.this)
					// .extra("couponid",
					// coupon.getString("id"))
					// .start();
					// } catch (JSONException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }
					// }
					// });
				}
			}

		});
		dresserCommentsListDataset = new ArrayList<>();
		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);

		layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
			@Override
			public int getSpanSize(int position) {
				return adapter.isPositionHeader(position) ? layoutManager
						.getSpanCount() : 1;
			}
		});
		rv_comments.setLayoutManager(layoutManager);
		rv_comments
				.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0, 0));
		rv_comments.setItemAnimator(new RecyclAnimation());
		adapter = new DresserCommentsListAdapter(
				DresserCommentsListActivity.this, dresserCommentsListDataset);
		rv_comments.setAdapter(adapter);
		// init sylist date
		iv_appointment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				BookActivity_.intent(DresserCommentsListActivity.this)
						.extra("id", dresserid).start();
			}
		});
		updateDataset(0);
	}

	@OnActivityResult(REQUEST_CODE)
	void onResult(Intent data) {
		if (data != null) {

		}
	}

	@Click
	void btn_dresser_type() {
		HairDresserFilterActivity_.intent(this).startForResult(REQUEST_CODE);
	}

	// values bought starLevel levlId studioId
	void updateDataset(int page) {
		StringBuilder url = new StringBuilder(get_dresser_comments_action);
		url.append("?");
		url.append("stylistinfoId=" + dresserid);
		url.append("&");
		url.append("page=" + page);
		getCommentsList(url.toString());
	}

	void getCommentsList(String url) {
		if (isMaxPage) {
			return;
		}

		aq.ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {

			@Override
			public void callback(String url, JSONArray object, AjaxStatus status) {
				// TODO Auto-generated method stub
				if (status.getCode() == -101) {
					Toast.makeText(aq.getContext(), "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_SHORT).show();
				} else {

					if (object != null && object.length() > 0) {
						for (int i = 0; i < object.length(); i++) {
							try {
								dresserCommentsListDataset.add(object
										.getJSONObject(i));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						if (object.length() < coutPerPage) {
							isMaxPage = true;
						}
					}
					if (dresserCommentsListDataset.size()<=0){
						dresserCommentsListDataset.add(null);
					}
					adapter.notifyDataSetChanged();

				}
			}

		});
	}

	class DresserCommentsListAdapter extends
			Adapter<RecyclerView.ViewHolder> {
		private static final int TYPER_PAGER = 0;
		private static final int TYPE_ITEM = 1;
		private static final int HEADER_PAGER_LAYOUT = 1;
		private OnNextPageShouldDownloadListener mOnNextPageShouldDownloadListener;
		private Context mContext;
		private DresserClickListener mOnCommentsClickListener;
		private List<JSONObject> array;

		public DresserCommentsListAdapter(Context con, List<JSONObject> array) {
			this.mContext = con;
			this.mOnCommentsClickListener = (DresserClickListener) con;
			this.array = array;
			this.mOnNextPageShouldDownloadListener = (OnNextPageShouldDownloadListener) con;

		}

		@Override
		public int getItemCount() {
			return array.size() + HEADER_PAGER_LAYOUT;
		}

		public boolean isPositionHeader(int position) {
			return position == 0;
		}

		@Override
		public int getItemViewType(int position) {
			if (isPositionHeader(position)) {
				return TYPER_PAGER;
			}
			return TYPE_ITEM;
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
				int viewType) {
			// TODO Auto-generated method stub

			if (viewType == TYPER_PAGER) {

				// View v = LayoutInflater.from(parent.getContext()).inflate(
				// R.layout.hair_style, parent, false);
				TextView v = new TextView(mContext);
				final DresserCommentsHeaderViewHolder headerHolder = new DresserCommentsHeaderViewHolder(
						v);
				return headerHolder;
			} else if (viewType == TYPE_ITEM) {
				if (array.size() == 1 && array.get(0) == null) {

					final View view = LayoutInflater.from(
							DresserCommentsListActivity.this).inflate(
							R.layout.noitem, parent, false);
					ImageView iv = (ImageView) view.findViewById(R.id.iv_default);
					TextView t = (TextView) view.findViewById(R.id.tv_content);
					iv.setImageResource(R.drawable.noitem_comment);
					t.setText("暂无评价信息");
					DresserCommentsViewHolder holder = new DresserCommentsViewHolder(view);
					holder.itemView.setTag(com.mlm.mlmapp.cons.Constants.IS_EMPTY);
					return holder;
				} else {
					DresserCommentsViewHolder holder;
					holder = new DresserCommentsViewHolder(LayoutInflater.from(
							DresserCommentsListActivity.this).inflate(
							R.layout.dresser_commnets_list_item, parent, false));
					return holder;
				}



			}
			return null;

		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder,
				int position) {
			// TODO Auto-generated method stub
			if (holder instanceof DresserCommentsViewHolder) {

				if (array.size() <= 0) {
					return;
				}
				JSONObject obj = array.get(position - HEADER_PAGER_LAYOUT);
				DresserCommentsViewHolder hHolder = (DresserCommentsViewHolder) holder;
				hHolder.tv_name.setText(getJsonString(obj, "name"));
				hHolder.tv_date.setText(getJsonString(obj, "comDate"));
				hHolder.tv_evalute.setText(getJsonString(obj, "content"));
				aq.id(hHolder.iv_headimg).image(
						getJsonString(obj, "iconPhotoUrl"), true, true, 0, 0,
						null, Constants.FADE_IN);
				hHolder.id = getJsonString(obj, "userId");

				JSONArray imagesArray = getJsonArray(obj, "photos");
				if (imagesArray.length() > 0) {

					hHolder.ll_images.setVisibility(View.VISIBLE);
					hHolder.ll_images.removeAllViews();
					try {
						for (int i = 0; i < imagesArray.length(); i++) {

							String url = CommonUtils.getJsonString(
									imagesArray.getJSONObject(i), "photoUrl");
							ImageView iv = new ImageView(
									DresserCommentsListActivity.this);
							LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
									(int) comments_images_edge,
									(int) comments_images_edge);

							lp.setMargins((int) commentImagesMargin, 0,
									(int) commentImagesMargin, 0);
							iv.setLayoutParams(lp);
							iv.setMaxHeight((int) comments_images_edge);
							iv.setMaxWidth((int) comments_images_edge);
							aq.id(iv).image(url, true, true, 0, 0, null,
									Constants.FADE_IN);
							hHolder.ll_images.addView(iv);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					hHolder.ll_images.setVisibility(View.GONE);
				}
			} else if (holder instanceof DresserCommentsHeaderViewHolder) {

			}
		}

		@Override
		public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
			// TODO Auto-generated method stub
			super.onViewAttachedToWindow(holder);

			getNextByPosition(holder.getPosition() - 1);

		}

		private int currentPage = 0;

		private void getNextByPosition(int position) {
			if (position % coutPerPage == 0) {
				// page start from 1 instead of 0,need +1,
				// e.g. @ position 0 should start downloading page 2
				// @ position 6 should start downloading page 3
				int page = position / coutPerPage + 1;
				// if(page<1){
				// page=1;
				// }
				// bigger than current page then need get nextpage
				if (currentPage < (page + 1)) {
					currentPage = page + 1;
					this.mOnNextPageShouldDownloadListener
							.onNextPageShouldDownload(currentPage);// next page
				}

			}

		}

		public class DresserCommentsHeaderViewHolder extends
				RecyclerView.ViewHolder {
			TextView t;

			public DresserCommentsHeaderViewHolder(View itemView) {
				super(itemView);
				// TODO Auto-generated constructor stub
				t = (TextView) itemView;
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				t.setBackgroundColor(Color.WHITE);
				t.setLayoutParams(lp);
				t.setGravity(Gravity.LEFT);
				t.setGravity(Gravity.CENTER_VERTICAL);
				t.setPadding((int) leftPadding, (int) leftPadding, 0, 0);
				t.setTextSize(TypedValue.COMPLEX_UNIT_PX,
						comments_title_padding);
				t.setTextColor(blacktext);
				t.setText("设计师评价");

			}

		}

		public class DresserCommentsViewHolder extends RecyclerView.ViewHolder {
			String id;
			ImageView iv_headimg;
			TextView tv_name;
			TextView tv_date;
			TextView tv_evalute;
			LinearLayout ll_images;

			public DresserCommentsViewHolder(View itemView) {
				super(itemView);
				this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
				this.tv_date = (TextView) itemView.findViewById(R.id.tv_date);
				this.tv_evalute = (TextView) itemView
						.findViewById(R.id.tv_evalute);
				this.iv_headimg = (ImageView) itemView
						.findViewById(R.id.iv_headimg);
				this.ll_images = (LinearLayout) itemView
						.findViewById(R.id.ll_images);
			}
		}
	}

	// as the function name !
	@Override
	public void onNextPageShouldDownload(int page) {
		// TODO Auto-generated method stub
		updateDataset(page);
	}

	@Override
	public void onAppointmentClick(String id) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "预约ID为：" + id + "的设计师", Toast.LENGTH_SHORT);
	}

	@Override
	public void onDresserClick(String id) {
		// TODO Auto-generated method stub
		HairDresserDetailActivity_.intent(DresserCommentsListActivity.this)
				.extra("id", id).start();
	}

	@Click
	void btn_home() {
		MainActivity_.intent(this).start();
	}

	@Click
	void btn_dresser() {
		HairDresserListActivity_.intent(this).start();
	}

	@Click
	void btn_appointment() {
		BookActivity_.intent(this).start();
	}

	@Click
	void btn_style() {
		HairStyleListActivity_.intent(this).start();
	}

	@Click
	void btn_userinfo() {
		UserInfoActivity_.intent(this).start();
	}

	@Override
	public void onNextPageShouldDownload(int nextPage, List list,
			Adapter adapter) {
		// TODO Auto-generated method stub

	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}
}
